//
//  JLActDetailViewController.m
//  BaseProject
//
//  Created by 王洋 on 2021/4/21.
//  Copyright © 2021 王洋. All rights reserved.
//
#import "JLActOrderCheckRequest.h"

#import "JLActCell.h"

#import "SubmitOrderViewController.h"
#import "OrderSegmentViewController.h"
#import "SelPayMethodViewController.h"

#import "JLActDetailViewController.h"

@interface JLActDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) UIButton *handleBtn;


@property (nonatomic, strong)NSMutableArray <CommonShopCartModel *>*dataArray;

@property (nonatomic, strong) CommonShopCartModel *handleModel;

@property (nonatomic, strong) JLActStatusModel *actStatusModel;


@end

@implementation JLActDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    WEAKSELF
    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
        if (isLogin) {
            
            [weakSelf initView];
            [weakSelf request_goodsList];
            
            [JLActOrderCheckRequest request_JLActStatusComption:^(BOOL success, JLActStatusModel * _Nonnull model) {
                if (success) {
                    weakSelf.actStatusModel = model;
                    [weakSelf handleWithModel:model];
                }
            }];
        }
    }];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)initView {
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    //屏幕常亮
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.navigationController.navigationBarHidden = YES;
#if RT_INTERACTIVE_PUSH
    self.rt_navigationController.rt_enableInteractivePush = YES;
#endif
    self.rt_disableInteractivePop = NO;

    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1);
    
    layer.colors = @[(__bridge id)[UIColorHex(0xff2d4a) colorWithAlphaComponent:1].CGColor, (__bridge id)[UIColorHex(0xf58c4f) colorWithAlphaComponent:1].CGColor];
    
    layer.frame = CGRectMake(0, 0, TTScreenWidth, TTScreenHeight);
    [self.view.layer insertSublayer:layer atIndex:0];
    
    
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    [self.view addSubview:self.handleBtn];
    [self.handleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-Bottom_SafeHeight - 20);
        make.centerX.mas_equalTo(0);
    }];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:backButton];
    [backButton setImage:[UIImage imageNamed:@"public_back_white"] forState:UIControlStateNormal];
    backButton.frame = CGRectMake(0, kStatusBarHeight, 20 + 32, kNavBarHeight);//20x20
    CGFloat top = (kNavBarHeight - 20) * 0.5;
    backButton.imageEdgeInsets = UIEdgeInsetsMake(top, 16, top, 16);
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TTScreenWidth, TTScreenWidth*2.06)];
    UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, TTScreenWidth, TTScreenWidth*2.06)];
//    imgv.backgroundColor = [UIColor redColor];
    [imgv setImage:[UIImage imageNamed:@"jl_act_head"]];
    [headerView addSubview:imgv];
    
    self.tableview.tableHeaderView = headerView;
    headerView.autoresizingMask = UIViewAutoresizingNone;
    
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)handleAction {
        
    switch (self.actStatusModel.type) {
        case JLActStatusType_none:{
            [self addJob];
            [self submitOrder];
        } break;
        case JLActStatusType_unpay:
        case JLActStatusType_finish:{
            [self handleWithModel:self.actStatusModel];
        } break;
        default:
            break;
    }
}

- (void)handleWithModel:(JLActStatusModel *)model {
    switch (model.type) {
        case JLActStatusType_none:{
        } break;
        case JLActStatusType_unpay:{

            [TT_Alert alert:@"您有未付款订单，请前往我的—订单—婚品订单内付款"
             cancleBtnTitle:@"取消"
               cancleAction:^{}
               doneBtnTitle:@"前往支付"
                 doneAction:^{
                    [self addJob];
                    [self firstPay:model.uoId];
                }];
            
        } break;
        case JLActStatusType_finish:{
            
            [self addJob];
            [self activationJob];
            
            [[BA_JobManager manager] checkTriggerWithType:BA_JobManagerType_JLAct comption:^(BOOL success) {
                if (success) {
                    JobModel *model = [[BA_JobManager manager] getJobWithType:BA_JobManagerType_JLAct];
                    [[TT_JumpManager sharedManager] jumpWithModel:model.actionModel completion:^(BOOL success, NSString * _Nonnull message) {
                        [[BA_JobManager manager] removeJobWithType:BA_JobManagerType_JLAct];
                    }];
                }
            }];
            
        } break;
        default:
            break;
    }
}

- (void)submitOrder {
    
    NSMutableArray <CommonShopCartModel *>*dataArray = @[].mutableCopy;
    for (CommonShopCartModel *model in self.dataArray) {
        model.sellerGoodsSpecs.goodsNum = 1;
        if (model.isSel) {
            [dataArray addObject:model];
        }
    }

    if (dataArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请先挑选商品"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    SubmitOrderViewController *vc = [[SubmitOrderViewController alloc] init];
    vc.dataArray = dataArray.mutableCopy;
    vc.activeType = @"2";
    [self.navigationController pushViewController:vc animated:YES];
}

//添加job
- (void)addJob {
    
    JobModel *model = [[JobModel alloc] init];
    model.jobType = BA_JobManagerType_JLAct;

    model.activationState = JobActivationType_wait;
    model.triggerState = JobTriggerType_none;
    
    HomeADItemEventModel *actionModel = [[HomeADItemEventModel alloc] init];
    actionModel.eventClickId = TT_JUMPTYPE_H5;
    actionModel.eventSellerId = @"https://www.myunshe.com/h5/index.html?id=71";
    model.actionModel = actionModel;
    [[BA_JobManager manager] addSingleJobWithModel:model];
}

- (void)activationJob {
    JobModel *activationJob = [[BA_JobManager manager] getJobWithType:BA_JobManagerType_JLAct];
    activationJob.activationState = JobActivationType_finish;
    activationJob.triggerState = JobTriggerType_wait;
    [[BA_JobManager manager] updateJobWithModel:activationJob];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (TTScreenWidth - 20)*0.43178 + 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return Bottom_SafeHeight + 80;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    for (CommonShopCartModel *model in self.dataArray) {
        model.isSel = NO;
    }
    self.dataArray[indexPath.row].isSel = YES;
    [self.tableview reloadData];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JLActCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JLActCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = UIColor.clearColor;
    return footer;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColor.clearColor;

        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"JLActCell" bundle:nil] forCellReuseIdentifier:@"JLActCellID"];
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _tableview;
}

- (UIButton *)handleBtn {
    if (!_handleBtn) {
        _handleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_handleBtn setImage:[UIImage imageNamed:@"act_handle_icon"] forState:UIControlStateNormal];
        [_handleBtn addTarget:self action:@selector(handleAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _handleBtn;
}

- (NSMutableArray<CommonShopCartModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (JLActStatusModel *)actStatusModel {
    if (!_actStatusModel) {
        _actStatusModel = [[JLActStatusModel alloc] init];
    }
    return _actStatusModel;
}

- (void)request_goodsList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@"4" forKey:@"type"];//婚品类型（ 1：精选，2：热卖3：新人专享0元购，4：锦鲤活动，5：推荐）
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_ActPackage];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                                
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < list.count; i++) {
                        
                        
                        
                        NSDictionary *listDic = list[i];
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            CommonPackageModel *packageModel = [CommonPackageModel modelWithJSON:listDic];
                            
                            CommonShopCartModel *cartModel = [[CommonShopCartModel alloc] init];
                            cartModel.sellerGoodsModel = packageModel;
                            
                            //店铺信息
                            cartModel.sellerModel.sellerId = packageModel.sellerId;
                            cartModel.sellerModel.sellerName = packageModel.sellerName;
                            cartModel.sellerId =  packageModel.sellerId;
                            
                            
                            NSArray *sellerGoodsSpecs = [listDic valueForKey:@"sellerGoodsSpecs"];
                            NSMutableDictionary *goodsSpec = @{}.mutableCopy;
                            if (sellerGoodsSpecs.count > 0) {
                                goodsSpec = sellerGoodsSpecs.firstObject;
                            }
                            
                            CommonSkuModel *skuModel = [CommonSkuModel modelWithDictionary:goodsSpec];
                            cartModel.sellerGoodsSpecs = skuModel;
                            cartModel.goodsId = skuModel.goodsId;
                            cartModel.sellerId = skuModel.sellerId;
                            cartModel.sgsId = skuModel.sgsId;
                            cartModel.goodsNum = 1;
                            [weakSelf.dataArray addObject:cartModel];
                        }
                    }
                    
                    [weakSelf.tableview reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
    }];
    
}

- (void)firstPay:(NSString *)uoid {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:uoid forKey:@"orderId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_PayOrderDJ];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                SelPayMethodModel *model = [SelPayMethodModel modelWithDictionary:resultDic];
                SelPayMethodViewController *vc = [[SelPayMethodViewController alloc] init];
                vc.entranceType = PayEntranceType_pro;
                vc.model = model;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
    }];
}

@end
